//
//  WBNetworkManager+Extension.swift
//  MyWeibo
//
//  Created by timw on 2017/3/29.
//  Copyright © 2017年 wuqc. All rights reserved.
//

import Foundation

extension WBNetworkManager {

    /// 加载微博数据字典数组
    ///
    /// - Parameter completion: 完成回调[list: 微博字典数组／是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0,completion: @escaping (_ list: [[String: Any]]?, _ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": since_id,
                      "max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            //let result1 = json as! [String: Any]
            //let result2 = result1["statuses"] as! [[String: Any]]
            
            let result = (json as? [String: Any])?["statuses"] as? [[String: Any]]
            
            completion(result, isSuccess)
        }
        
    }
    
    /// 加载未读微博数量
    ///
    /// - Parameter completion: 完成回调（未读微博数量）-- 定时刷新，不需要提示是否失败
    func unreadCount(completion: @escaping (_ count: Int) -> ()) {
        guard let uids = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/counts.json"
        let params = ["uids": uids]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            //print(json)
            let result1 = json as? [[String: Any]]
            let result2 = result1?[0]["statuses_count"] as? Int
            completion(result2 ?? 0)
        }
    }
}

extension WBNetworkManager {
    /// 网络请求异步到底应该返回什么？ - 需要什么返回什么
    /// 加载 AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id" : WBAppKey,
                      "client_secret" : WBAppSecret,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : WBRedirectURI,
        
        ]
        // 发起网络请求
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            // print(json)
            
            // 直接用字典设置 userAccount 的属性
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
            
            // print(self.userAccount.access_token)
            // 保存模型
            self.userAccount.saveAccount()
            
            // 完成回调
            completion(isSuccess)
        }
    }
}
